package com.ch.mobilesha.base;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;

import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import com.ch.mobilesha.common.CommonRequestUrl;
import com.ch.mobilesha.net.MyHttpAPI;
import com.ch.mobilesha.tools.UtilLog;

public class BaseCrashHandler  implements UncaughtExceptionHandler {
	private static Context context;
	private static BaseCrashHandler baseCrashHandler;
	private MyHttpAPI myHttpAPI = new MyHttpAPI(CommonRequestUrl.AddErrorService);
	public void uncaughtException(Thread thread,final Throwable ex) {
		JSONObject params = new JSONObject();
		try{
			UtilLog.e("error", getErrorInfo(ex));
			params.put("version",getVersionInfo());
			params.put("errormessage",getErrorInfo(ex));
			params.put("mobileinfo",getMobileInfo());
			myHttpAPI.requestForJson(params);
		}catch (Exception e) {
			e.printStackTrace();
		}
		MobileShaApplication.getSelf().exit();
		int id = android.os.Process.myPid();
		android.os.Process.killProcess(id);
		
	}

	private BaseCrashHandler() {

	}
	
	public static BaseCrashHandler getBaseCrashHandler(Context context){
		BaseCrashHandler.context = context;
		if(baseCrashHandler!=null){
			return baseCrashHandler;
		}else{
			baseCrashHandler = new BaseCrashHandler();
			return baseCrashHandler;
		}
	}

	/**
	 * 　　* 获取错误的信息 　　* @param arg1 　　* @return 　　
	 */
	private String getErrorInfo(Throwable arg1) {
		Writer writer = new StringWriter();
		PrintWriter pw = new PrintWriter(writer);
		arg1.printStackTrace(pw);
		pw.close();
		String error = writer.toString();
		return error;
	}

	/**
	 * 　　* 获取手机的硬件信息 　　* @return 　　
	 */
	private String getMobileInfo() {
		StringBuffer sb = new StringBuffer();
		// 通过反射获取系统的硬件信息
		try {
			Field[] fields = Build.class.getDeclaredFields();
			for (Field field : fields) {
				// 暴力反射 ,获取私有的信息
				field.setAccessible(true);
				String name = field.getName();
				String value = field.get(null).toString();
				sb.append(name + "=" + value);
				sb.append("\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 　　* 获取手机的版本信息 　　* @return 　　
	 */
	private String getVersionInfo() {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
			return info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
			return "版本号未知";
		}
	}
}
